# -*- coding:utf-8 -*-


class Empty(Exception):
    """Error: attempting to access an element from an empty container"""

    pass


class ArrayStack:
    """LIFO Stack implementation using a Python list class as underlying storage"""

    def __init__(self):
        self._stack = []

    def __len__(self):
        return len(self._stack)

    def is_empty(self):
        return len(self._stack) == 0

    def push(self, item):
        self._stack.append(item)

    def pop(self):
        if self.is_empty():
            raise Empty("Stack is empty!")
        return self._stack.pop()

    def top(self):
        if self.is_empty():
            raise Empty("Stack is empty!")
        return self._stack[-1]


def reverse_file(file_name):
    """Reverse a file line by line, using ArrayStack"""
    s = ArrayStack()
    with open(file_name, "r") as f:
        for line in f.readlines():
            s.push(line.rstrip("\n"))
    with open(file_name, "w") as f:
        while not s.is_empty():
            f.write(s.pop() + "\n")


def is_matched(expression):
    """Estimate whether all delimiters are properly matched in the expression"""
    lefty = "(}]"
    righty = ")}]"
    s = ArrayStack()
    for c in expression:
        if c in lefty:
            s.push(c)
        elif c in righty:
            if s.is_empty():
                return False
            if righty.index(c) != lefty.index(s.pop()):
                return False
    return s.is_empty()


def is_matched_html(html):
    """Estimate whether all HTML tags are properly matched"""
    s = ArrayStack()
    i = html.find("<")
    while i != -1:
        j = html.find(">", i + 1)
        if j == -1:
            return False
        tag = html[i + 1 : j]
        if not tag.startswith("/"):
            s.push(tag)
        else:
            if s.is_empty():
                return False
            if tag[1:] != s.pop():
                return False
        i = html.find("<", j + 1)
    return s.is_empty()


if __name__ == "__main__":
    reverse_file("test.txt")
